package com.hdax.dm.utils.Token;

import cn.hutool.crypto.asymmetric.RSA;
import io.jsonwebtoken.*;

import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class TokenUtil {

    private static String private_key = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDdsVMLTdmcXJdV/2SA8N8w+bV1txC9jgzfJVrM9Z7aLo6oLHhbG54xey6/OEbxbe1nBAnmgSBRI7O3psTa4plF0YlHcZGeO16JSwPn3/2eaSeslAEXmuxU/SHLiKg8Y5TwuWL9NOeblB02Z/a1UeEP0nicTlmZ213yn+lDdNLpPzgg4sqB8v9P2UmQTQDwmz7nkh0WIBTH165HBjFxtjX9Mbjt9BH+2NhMqJ+nVzbI3yE3AL1nNFe1KMHXTLO+0j4sBNqw6iQnxXeQsIoDyUspKL7lFyIs4wdEFGK996AO11WMzm4G7Q3oZAzW2EYREZg/XOB+rs5233596wByXtRfAgMBAAECggEAISFY6b2OocFslFuAZ4yXrjgDGD5tcAaEgeyRL0QdozmF9DgBHIx6Dab9C3Kbl4T4D4cY+6ucasPNHcr8bEGk6jwwKc8dFeqFbDsbsFFXE49fcHkF2MM8Qk8597LKgYvYPElYM8LuQd/WpcTPp7U+zyCDCcjjtwyDc7jWIVCaHGUg7RfXudnyaHYbMwQG7GuDGWp1tba93JtJdcnJ4sVjlAaxCWQJ3HwPYlR2JIMOmfTTDUIUULKixDQYamuA2lMBsX9ZraLZwnhZjlPCv7gkvXyv6maANBnkgNQhOwZuMUK7Yb+4ot2wuV5iJ0UXfN/ZFQriv2KPuvnh382zpwTS8QKBgQD7g8JFT23hAIpfpYlF/5gXsn8dJ4SVLkmROCgo/k/7ZPnWnsuJiNbrD4UieqkS68MyH6yregXrYpF0qOq35xoLki6Snw0uNKLledznaa2KY0YdKzC335POwb881mJfLQRbsHfY+rziEzKCK4M6jID86iL8X5t9Tu1UgEM5qqt2+wKBgQDhpWtBP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YP1zgfq7Odt9+fesAcl7UXwIDAQAB";

    //创建时间
    public static Date createDate=new Date();
    //过期时间
    public static Date expireDate=new Date(createDate.getTime()+180*60*1000); //验签时间

    //生成token
    public static String createToken(String id,String name){
        RSA rsa=new RSA(private_key,null);  //利用hutool创建RSA
        RSAPrivateKey privateKey= (RSAPrivateKey) rsa.getPrivateKey();
        JwtBuilder builder= Jwts.builder();
        builder.claim("username",name);
        builder.setIssuedAt(createDate);
        builder.setExpiration(expireDate);
        builder.setId(id);  //设置唯一标识
        //生产签名的信息
        builder.signWith(privateKey, SignatureAlgorithm.RS256);  //RS256算法
        String token= builder.compact();
        return token;
    }

    //解密
    public static String parseToken(String token) {
        RSA rsa = new RSA(null, public_key);  //利用hutool创建RSA
        RSAPublicKey rsaPublicKey = (RSAPublicKey) rsa.getPublicKey();
        //解析的构建器
        JwtParserBuilder parserBuilder = Jwts.parserBuilder();
        parserBuilder.setSigningKey(rsaPublicKey);
        JwtParser jwtParser = parserBuilder.build();
        String id=null;
        try {
            Claims claims  = jwtParser.parseClaimsJws(token).getBody();
            id= claims.getId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return id;
    }
}
